package org.lgiavedoni.android.franq.command.db;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.lgiavedoni.android.franq.core.command.Command;
import org.lgiavedoni.android.franq.service.communication.CommunicationService;
import org.lgiavedoni.android.franq.service.db.DbService;
import org.lgiavedoni.android.franq.util.collection.CollectionUtils;

public class DbCommand extends Command {

	private static final String OPTION_ENTYTIES = "entyties";
	private static final String OPTION_DELETE = "delete";
	private static final String OPTION_EXPORT = "export";

	@Override
	public String getCommandText() {
		return "db";
	}

	@Override
	public void setOptions(Options options) {
		options.addOption(OPTION_ENTYTIES, false, "Count all entyties in the DB");
		options.addOption(OPTION_DELETE, false, "Delete the DB");
		options.addOption(OPTION_EXPORT, false, "Export the DB");
	}

	@Override
	public boolean execute(CommandLine cmd) throws Exception {
		if (!DbService.inst.isStarted()) {
			CommunicationService.inst.sendDefaultTextMessage("Sorry, the DB service is not running.");
			return true;
		}

		// entyties

		if (cmd.hasOption(OPTION_ENTYTIES)) {
			CommunicationService.inst.sendDefaultTextMessage(CollectionUtils.toString(DbService.inst.countEntyties(), ": ", "\n"));
			return true;
		}

		if (cmd.hasOption(OPTION_DELETE)) {
			DbService.inst.deleteDataBase();
			CommunicationService.inst.sendDefaultTextMessage("The data base has been deleted.");
			return true;
		}

		if (cmd.hasOption(OPTION_EXPORT)) {
			String export = DbService.inst.exportDataBase();
			CommunicationService.inst.sendDefaultTextMessage("The data base has been exported [" + export + "].");
			return true;
		}

		return false;
	}

}
